#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>
#include <string>

class TranslateClient
{
public:
    TranslateClient(const std::string sip, int sport)
        : _latch(1),
          _client(_loopthread.startLoop(), muduo::net::InetAddress(sip, sport), "TranslateClient")
    {
        _client.setConnectionCallback(std::bind(&TranslateClient::OnConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&TranslateClient::OnMessage, this, std::placeholders::_1,
                                             std::placeholders::_2, std::placeholders::_3));
    }
    // 连接服务器，需要阻塞等待连接成功后返回
    void Connect()
    {
        _client.connect();
        _latch.wait(); // 阻塞等待连接成功
    }

    bool Send(const std::string &msg)
    {
        if (_conn->connected())
        {
            _conn->send(msg);
            return true;
        }
        return false;
    }

private:
    // 连接建立成功后的回调函数，用来唤醒上面的connect连接时的阻塞
    void OnConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if (conn->connected())
        {
            _latch.countDown(); // 当连接成功后，唤醒主线程Connect中的阻塞
            _conn = conn;
        }
        else
        {
            _conn.reset(); // 连接关闭后的操作
        }
    }

    void OnMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buffer, muduo::Timestamp)
    {
        std::cout << "翻译结果：" << buffer->retrieveAllAsString() << std::endl;
    }

private:
    muduo::CountDownLatch _latch;
    muduo::net::EventLoopThread _loopthread; // 使用一个线程来进行epoll循环处理
    muduo::net::TcpConnectionPtr _conn;
    muduo::net::TcpClient _client;
};

// 客户端
int main()
{
    TranslateClient client("127.0.0.1", 8080);
    // 1.客户端连接服务器
    client.Connect();

    // 2.客户端开始发送数据给服务器
    while (1)
    {
        std::string msg;
        std::cin >> msg;
        client.Send(msg);
    }

    return 0;
}